from tornado import gen

from libs.base.model import BaseModel
from libs.tools.widget import Common


class StoreListModel(BaseModel):

    def __init__(self, handler):
        super(StoreListModel, self).__init__(handler)
        self.handler = handler
        self.data = {}

    async def fetch_list(self, opts):
        print(opts,'111')
        """
        获取门店列表数据
        """
        # 仅用于测试

        list_sql, count_sql, values = self._parse_list_sql(opts)
        data_list = await self._fetch_list_data(list_sql, values)
        print(data_list,'88')
        total_count = await self._total_count(count_sql, values, data_list, opts)
        data = Common.list_model_data(data_list, total_count, opts)
        return self.set_res_info(0, data=data)


    def _parse_list_sql(self, opts):
        sql_base = """
            SELECT store_id, store_name, country_code, province_code, city_code,
                store_address, brand_count, user_id, store_status, store_images,
                create_by, create_time
            FROM store_info
            WHERE {where}
            {order} {limit}
        """

        queries, values = [], []
        print(queries,values,'values')
        opts["key_allow"] = [
            ['store_name', '{key}', 'like'],
            ['store_id', '{key}'],
            ['user_id', '{key}'],
            ['store_status', '{key}'],
            ['province_code', '{key}'],
            ['city_code', '{key}'],
            ['data_status=1', '{key}', 'raw']
        ]
        opts["order_allow"] = [["store_id", "{key}"], ["brand_count", "{key}"]]
        infos = Common.parse_where(queries, values, opts)
        print('infos',infos)
        list_sql = sql_base.format(**infos)
        count_sql = Common.parse_count_sql(infos["where"], sql_base)
        return list_sql, count_sql, values

    async def _fetch_list_data(self, list_sql, values):
        await self.db.execute(list_sql, values)
        data_list = self.db.fetchall()
        await self.get_users(data_list, ["user_id", "create_by"])
        return data_list


class StoreInfoModel(BaseModel):

    def __init__(self, handler, store_id=None):
        super(StoreInfoModel, self).__init__(handler)
        self.handler = handler
        self.store_id = store_id
        self.data = {}

    async def fetch_info(self, opts):
        """
        获取门店基本信息
        """
        # 仅用于测试
        if opts.get("delay") and opts["delay"] > 0:
            await gen.sleep(opts.pop("delay"))
        # 校验id是否存在
        flag = await self._check_data_exist()
        if flag != 0:
            return self.set_res_info(flag)
        # fetch
        selects = [
            "store_id", "store_name", "country_code", "province_code", "city_code",
            "store_address", "brand_count", "user_id", "store_status", "store_images",
            "create_by", "create_time"
        ]
        await self.db.select("store_info", selects, {"store_id": self.store_id})
        info = self.db.fetchone()
        await self.get_users(info, ["user_id", "create_by"])
        return self.set_res_info(0, data=info)

    async def insert_info(self, opts):
        """
        新增门店信息
        """
        # 校验信息是否重复
        flag = await self._check_data_unique(opts)
        if flag != 0:
            return self.set_res_info(flag)
        # insert
        self.fill_create_info(opts)
        store_id = await self.db.insert("store_info", opts)
        if not self.db.errors:
            await self.db.commit()
        return self.set_res_info(0, data={"store_id": store_id})

    async def update_info(self, opts):
        """
        修改门店基本信息
        """
        # 校验id是否存在
        flag = await self._check_data_exist()
        if flag != 0:
            return self.set_res_info(flag)
        # 校验是否重复
        flag = await self._check_data_unique(opts)
        if flag != 0:
            return self.set_res_info(flag)
        # update
        wheres = {"store_id": self.store_id, "data_status": 1}
        await self.db.update("store_info", opts, wheres)
        if not self.db.errors:
            await self.db.commit()
        return self.set_res_info(0)

    async def delete_info(self):
        """
        软删除门店
        """
        # 校验id是否存在
        flag = await self._check_data_exist()
        if flag != 0:
            return self.set_res_info(flag)
        # delete
        wheres = {"store_id": self.store_id, "data_status": 1}
        await self.db.update("store_info", {"data_status": -1}, wheres)
        if not self.db.errors:
            await self.db.commit()
        return self.set_res_info(0)

    async def _check_data_exist(self):
        # 校验数据ID是否存在
        wheres = {"store_id": self.store_id, "data_status": 1}
        await self.db.select("store_info", "Count", wheres)
        count = self.db.fetchone().get("Count")
        # 不存在, 返回状态码4005; 存在, 返回0
        return 4005 if count != 1 else 0

    async def _check_data_unique(self, opts):
        # 校验主字段是否重复
        wheres = {
            "store_id!": self.store_id or 0,
            "store_name": opts["store_name"],
            "data_status": 1
        }
        await self.db.select("store_info", "Count", wheres)
        count = self.db.fetchone().get("Count")
        # 重复, 返回状态码4008; 不重复, 返回0
        return 4008 if count > 0 else 0
